package main.java.com.negromotad.genetics;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jgap.Chromosome;
import org.jgap.Configuration;
import org.jgap.Gene;
import org.jgap.IChromosome;
import org.jgap.InvalidConfigurationException;
import org.jgap.impl.IntegerGene;

public class TMChromosome extends Chromosome {

	/**
	 * Auto generated ID
	 */
	private static final long serialVersionUID = 9215790126477883243L;
	private List<String> genes;

	/**
	 * Create a chromosome with genes.
	 * 
	 * @param aConfiguration
	 * @param aInitialGenes
	 * @throws InvalidConfigurationException
	 * @throws InvalidConfigurationException
	 */
	public TMChromosome(Configuration aConfiguration, List<String> genes)
			throws InvalidConfigurationException {
		super(aConfiguration);
		Gene[] aInitialGenes = new Gene[genes.size()];
		for (int i = 0; i < genes.size(); i++) {
			aInitialGenes[i] = new IntegerGene(aConfiguration, 0, 100);
		}
		this.setGenes(aInitialGenes);
		this.genes = genes;
	}

	public TMChromosome(Configuration aConfiguration, List<String> genes,
			IChromosome chromosome) throws InvalidConfigurationException {
		super(aConfiguration);
		this.setGenes(chromosome.getGenes());
		this.genes = genes;
	}

	public Map<String, Integer> getChromosome() {
		Map<String, Integer> chromosome = new HashMap<String, Integer>();
		for (int i = 0; i < this.getGenes().length; i++) {
			chromosome.put((String) genes.get(i), (Integer) this.getGene(i)
					.getAllele());
		}
		return chromosome;
	}

	public double getRisk(Double[][] entry, int expectative, int rows, int cols) {
		double totalColumn;
		double totalRisk = 0.0;
		// Integer[] test = {10,0,90};
		for (int i = 0; i < rows; i++) {
			totalColumn = 0.0;
			for (int j = 0; j < cols; j++) {
				totalColumn += ((Integer) this.getGene(j).getAllele())
						* entry[i][j] / 100;
				// totalColumn += test[j]*entry[i][j]/100;
			}
			if (totalColumn < expectative) {
				totalRisk += expectative - totalColumn;
			}
		}
		return totalRisk;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((genes == null) ? 0 : genes.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (getClass() != obj.getClass())
			return false;
		TMChromosome other = (TMChromosome) obj;
		if (genes == null) {
			if (other.genes != null)
				return false;
		} else if (!genes.equals(other.genes))
			return false;
		else {
			Gene[] genesOther = other.getGenes();
			Gene[] genesThis = this.getGenes();
			for (int i = 0; i < this.getGenes().length; i++) {
				if (!genesThis[i].getAllele().toString().equals(
						genesOther[i].getAllele().toString()))
					return false;
			}
		}
		return true;
	}

}
